package org.ccheng.xztx.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import io.reactivex.Observable;
import org.ccheng.xztx.domain.DevilInfo;
import org.ccheng.xztx.service.DevilService;
import org.ccheng.xztx.util.Api;
import org.ccheng.xztx.util.ApiConstants;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 魔神塔
 */
@Service
public class DevilServiceImpl implements DevilService {

    private static final String I = "[魔神塔]：";

    public DevilInfo getInfo() {
        return Api.get(ApiConstants.API_DEVIL_INDEX, DevilInfo.class);
    }

    /**
     * 开始寻觅
     */
    public void random() {
        System.out.println("[魔神塔]：开始自动寻觅");

        DevilInfo info = getInfo();

        if (Integer.valueOf(info.getNum()) == 0) {
            Api.out(I, "寻觅次数为 " + info.getNum());
            Api.out(I, "寻觅结束");

        } else {
            String response = Api.get(ApiConstants.API_DEVIL_RANDOM);
            String result = null;

            // 判断灵草采摘事件
            result = ReUtil.get("遇到灵草，选择摘取方式：", response, 0);
            if (StrUtil.isNotEmpty(result)) {
                Api.out(I, result + "快步摘取 潜伏靠近");

                long type = RandomUtil.randomLong(0, 2);
                Api.out(I, "随机执行：" + (type == 0 ? "快步摘取" : "潜伏靠近"));
                pick(type);
            }

            // 遇到魔兽奖励
            result = ReUtil.get("遇到魔兽，击杀后获得了\\d+功勋！", response, 0);
            if (StrUtil.isNotEmpty(result)) {
                Api.out(I, result);
            }

            // 宝物奖励
            result = ReUtil.get("找到了上仙掉落的宝物：\\S+(?=<)", response, 0);
            if (StrUtil.isNotEmpty(result)) {
                Api.out(I, result);
            }

            // 矿物奖励
            result = ReUtil.get("遇到魔神矿脉，\\S+(?=<)", response, 0);
            if (StrUtil.isNotEmpty(result)) {
                Api.out(I, result);
            }
        }
    }

    public void pick(long type) {
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("type", type);

        String response = Api.get(ApiConstants.API_DEVIL_PICK, params);

        String result = null;

        System.out.print("");
        // 获取灵草奖励结果
        result = ReUtil.get("(成功摘取.{0,50}[×+]\\d+)", response, 0);
        if (StrUtil.isNotEmpty(result)) {
            Api.out(I, result);
        }

        // 灵草溜走了
        result = ReUtil.get("很遗憾，灵草溜走了！", response, 0);
        if (StrUtil.isNotEmpty(result)) {
            Api.out(I, result);
        }
    }

    public void autoRandom() {
        DevilInfo info = getInfo();
        int num = Integer.valueOf(info.getNum());

        for (int i = 0; i < num; i++) {
            random();
        }

        Api.out(I, "寻觅结束");
        Api.out(I, "共执行：" + num + "次");
    }
}
